/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jeff.studyclient.ui;

import com.jeff.studyclient.Application;
import com.jeff.studyclient.ui.renderer.TextBox;
import com.jeff.studyclient.util.ImageUtils;
import com.jeff.studyclient.util.StyleUtils;
import com.jeff.studyclient.vo.LoginResult;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.JTextComponent;

/**
 *
 * @author zhou.zhefu
 */
public class LoginDialog extends JFrame {
    private JLabel lblUserName;
    private JLabel lblPassword;
    private JTextField txtUserName;
    private JPasswordField pfPassword;
    private JButton btnLogin;
    private JLabel lblBackground;
    private JLabel lblError;
    private JPanel mainPnl;
    

    public LoginDialog() throws HeadlessException {
        initComponents();
        
        setTitle("Login Dialog");
//        restSession = (RestSession) SpringUtils.getBean("restSession");
        
        lblBackground = new JLabel(ImageUtils.getSplashIcon());
        
        final int maxLength = 30;
        lblUserName = new JLabel("User Name");
        lblUserName.setFont(StyleUtils.TEXT_FONT);
        lblPassword = new JLabel("Password");
        lblPassword.setFont(StyleUtils.TEXT_FONT);
//        lblPassword.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));
        
        txtUserName = new TextBox(maxLength);
		txtUserName.setName("username");
		txtUserName.setToolTipText("User Name to Login");
		txtUserName.setPreferredSize(new java.awt.Dimension(120, 21));
		txtUserName.setFont(StyleUtils.DEFAULT_FONT);
        
        pfPassword = new JPasswordField();
		pfPassword.setName("password");
		AbstractDocument doc = (AbstractDocument) pfPassword.getDocument();
		doc.setDocumentFilter(new TextBox.FixedSizeFilter(maxLength));
		pfPassword.setToolTipText("Password to Login");
		pfPassword.setPreferredSize(new java.awt.Dimension(120, 21));
		pfPassword.setFont(StyleUtils.DEFAULT_FONT);
        
        btnLogin = new JButton("Login");
        btnLogin.setFont(StyleUtils.TEXT_FONT);
        btnLogin.setName("login");
        
        lblError = new JLabel();
		lblError.setForeground(Color.RED);
		lblError.setHorizontalAlignment(SwingConstants.CENTER);
		lblError.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
        
        mainPnl = new JPanel();
		mainPnl.setLayout(new FlowLayout());
		mainPnl.setBorder(BorderFactory.createEmptyBorder(15, 0, 10, 0));
		mainPnl.add(lblUserName);
		mainPnl.add(txtUserName);
		mainPnl.add(lblPassword);
		mainPnl.add(pfPassword);
		mainPnl.add(Box.createHorizontalStrut(15));
		mainPnl.add(btnLogin);
        
        
        getContentPane().add(lblBackground, BorderLayout.NORTH);
        getContentPane().add(mainPnl, BorderLayout.CENTER);
        getContentPane().add(lblError, BorderLayout.SOUTH);
        
        setBounds(0, 0, 705, 340);
		setLocationRelativeTo(null);
        
        btnLogin.addMouseListener(new LoginClickedListener());
        addKeyboardActions();
        
        txtUserName.requestFocusInWindow();//auto on focus when window rendered
        
        FocusListener focusAction = new FocusAction();
        txtUserName.addFocusListener(focusAction);
        pfPassword.addFocusListener(focusAction);
//        lblError.setText("Fuck, wrong again");
    }

    private void initComponents() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        pack();
    }

    private void addKeyboardActions() {
        final int keyModifiers = 0;//KeyEvent.SHIFT_DOWN_MASK;//by default should be 0, here just for experiment of modifier combination
        KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, keyModifiers);
        
        Action escListener = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //exit app, might come with some cleanup jobs
                System.exit(0);
            }
            
        };
        
        txtUserName.registerKeyboardAction(escListener, escKey, JComponent.WHEN_FOCUSED);
        pfPassword.registerKeyboardAction(escListener, escKey, JComponent.WHEN_FOCUSED);
        mainPnl.registerKeyboardAction(escListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
    
    public class LoginClickedListener implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            //proceed login action
            if (e.getSource() == btnLogin) {
                login();
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            //do nothing;
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            mouseClicked(e);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            //do nothing;
        }

        @Override
        public void mouseExited(MouseEvent e) {
            //do nothing;
        }
        
    }
    
    private class FocusAction implements FocusListener {

        @Override
        public void focusGained(FocusEvent e) {
            //changing the background and make existing content selected
            Object field = e.getSource();
            if (field instanceof JTextComponent) {
                JTextComponent castField = (JTextComponent) field;
                castField.setBackground(StyleUtils.INPUT_FOCUS_BACKGROUND);
                if (!castField.getText().isEmpty()) {
                    castField.selectAll();
                }
            }
        }

        @Override
        public void focusLost(FocusEvent e) {
            //changing the background back to normal
            Object field = e.getSource();
            if (field instanceof JTextComponent) {
                JTextComponent castField = (JTextComponent) field;
                castField.setBackground(StyleUtils.INPUT_BACKGROUND);
            }
        }
        
    } 
    
    private void login() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                execLogin();
            }
        });
    }
    
    private void execLogin() {
        String userName = txtUserName.getText().trim();
		String password = String.valueOf(pfPassword.getPassword()).trim();

		if (userName == null || userName.length() == 0 || password == null || password.length() == 0) {
			return;
		}

		this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		lblError.setText("");
        Exception ex = null;
        LoginResult result = new LoginResult();
        try {
//			result = restSession.login(userName, password);
		} catch (Exception e) {
			System.out.println("Failed: " + e.getMessage());
			ex = e;
		}
		this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

		if (ex != null) {
//			MsgBox.showError(ERROR_CONNECTING_TITLE, ERROR_CONNECTING_MSG);
			return;
		}

		if (!result.isSuccess()) {
			lblError.setText(result.getMsgCode() + " - " + result.getMsgDesc());
			pfPassword.setText("");
		} else {
			System.out.println("User Logged In: " + userName);

			setVisible(false);
			txtUserName.setText("");
			pfPassword.setText("");
			txtUserName.requestFocusInWindow();

			Application.startup(result);
		}
    }
    
}
